package cn.qn.framwork.security;

import cn.qn.dto.security.MemberDTO;
import cn.qn.moudle.security.MemberAccount;
import cn.qn.moudle.security.Permission;
import cn.qn.moudle.security.Role;
import cn.qn.service.member.MemberService;
import cn.qn.service.security.RoleService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by yangyibo on 17/2/7.
 */
@Component
public class MemberAccountService implements UserDetailsService {
    @Reference(check = false, timeout = 30000)
    private MemberService memberService;
    @Reference(check = false, timeout = 30000)
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String userId) { //重写loadUserByUsername 方法获得 userdetails 类型用户

        MemberAccount memberAccount = memberService.findMemberAccountByUserId(userId);
        if (memberAccount == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }

        List<Role> roles = roleService.findByUserId(userId);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        memberAccount.setAuthorities(authorities);
        return memberAccount;
    }

    public MemberAccount getUserByUserId(String userId) {
        return memberService.findMemberAccountByUserId(userId);
    }

    /**
     * 创建用户信息
     * @param memberAccount
     * @return
     */
    public MemberDTO createMemberDTO(MemberAccount memberAccount) {
        MemberDTO member=new MemberDTO();
        BeanUtils.copyProperties(memberAccount,member);
        List<Role> roles = memberService.findRoleByMemberId(memberAccount.getUserId());
        member.setRoleList(roles);
        Set<String> ps = new HashSet<>();
        List<Permission>  permissions = findAllPermission();
        permissions.forEach(p->{
            ps.add(p.getPermission());
        });
        member.setPermissions(ps);
        return member;
    }

    public List<Permission> findAllPermission(){
        return memberService.finAllPermission();
    }

    public List<Role> findRolesByPermissionId(Integer permissionId) {
        return memberService.findRolesByPermissionId(permissionId);
    }
}